package com.party.jackclientandroid.ui_mine;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.gavin.com.library.StickyDecoration;
import com.gavin.com.library.listener.GroupListener;
import com.gavin.com.library.listener.OnGroupClickListener;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.ConsumeRecord;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.DateUtils;
import com.party.jackclientandroid.utils.DensityUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的钱包-明细
 */
public class TradeListActivity extends BaseActivityTitle {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    UserService userService;
    int page;
    int pageSize = ConstUtils.PAGE_SIZE;
    List<ConsumeRecord> dataList = new ArrayList<>();
    CommonAdapter<ConsumeRecord> commonAdapter;
    @BindView(R.id.tv_trade_list_expenses)
    TextView tvTradeListExpenses;
    @BindView(R.id.tv_trade_list_income)
    TextView tvTradeListIncome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade_list);
        ButterKnife.bind(this);
        initData();
        initListener();
        userTotalIncomeAndPay();
    }

    protected void initData() {
        setMiddleText("明细");
        userService = new UserService(this);
        commonAdapter = new CommonAdapter<ConsumeRecord>(mActivity, R.layout.item_trade_list, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder, ConsumeRecord item, int position) {
//                if (item.getTradeRecordType() == 0) {
//
//                }
                viewHolder.setText(R.id.tv_content_1, item.getRemarks());
                viewHolder.setText(R.id.tv_trade_list_time, item.getCreateTime());
                viewHolder.setText(R.id.tv_content_2, "¥ " + item.getXiapinCoin());
                viewHolder.setText(R.id.tv_content_3, "¥ " + item.getValue());
            }
        };
        StickyDecoration decoration = StickyDecoration.Builder
                .init(new GroupListener() {
                    @Override
                    public String getGroupName(int position) {
                        //组名回调
                        if (dataList.size() > position && position > -1) {
                            //获取组名，用于判断是否是同一组
                            return dataList.get(position).getCreateTime();
                        }
                        return null;
                    }
                })
                .setGroupBackground(Color.parseColor("#F4F4F4"))
                .setGroupHeight(DensityUtils.dip2px(mActivity, 35))
                .setDivideColor(Color.parseColor("#F6F6F6"))
                .setDivideHeight(DensityUtils.dip2px(mActivity, 1))
                .setGroupTextColor(Color.parseColor("#9F9F9F"))
                .setGroupTextSize(DensityUtils.sp2px(this, 15))
                .setTextSideMargin(DensityUtils.dip2px(this, 10))
                .setOnClickListener(new OnGroupClickListener() {
                    @Override
                    public void onClick(int position, int id) {
                        System.out.println();
                    }
                })
                .build();
        LinearLayoutManager manager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setAdapter(commonAdapter);
    }

    protected void initListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                System.out.println();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getNeedData();
            }
        });
        mRefreshLayout.autoRefresh();
    }

    private void getNeedData() {
        page = 1;
        addDisposableIoMain(userService.getUserConsumeRecord(page, pageSize), new DefaultConsumer<List<ConsumeRecord>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<ConsumeRecord>> result) {
                dataList.clear();
                if (result.getData() != null && result.getData().size() > 0) {
                    for (ConsumeRecord bean : result.getData()) {
                        bean.setCreateTime(DateUtils.formatDate(new Date(bean.getCreate())));
                    }
                    dataList.addAll(result.getData());
                }
                commonAdapter.notifyDataSetChanged();
                mRefreshLayout.finishRefresh();
            }
        });
    }

    private void loadMoreData() {
        page++;
        addDisposableIoMain(userService.getUserConsumeRecord(page, pageSize), new DefaultConsumer<List<ConsumeRecord>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<ConsumeRecord>> baseBean) {
                List<ConsumeRecord> data = baseBean.getData();
                boolean noMoreData = false;
                if (data != null && data.size() > 0) {
                    for (ConsumeRecord bean : data) {
                        bean.setCreateTime(DateUtils.formatDate(new Date(bean.getCreate())));
                    }
                    dataList.addAll(data);
                    if (data.size() <= ConstUtils.PAGE_SIZE) {
                        noMoreData = true;
                    }
                } else {
                    noMoreData = true;
                }
                commonAdapter.notifyDataSetChanged();
                // 没有更多数据了
                if (noMoreData) {
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    mRefreshLayout.finishLoadMore();
                }
            }
        });
    }

    //收支接口
    private void userTotalIncomeAndPay() {
        addDisposableIoMain(userService.getUserTotalIncomeAndPayList(), new DefaultConsumer<List<CommonResult>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<CommonResult>> result) {
                List<CommonResult> commonResultList = result.getData();
                for (CommonResult commonResult : commonResultList) {
                    if (commonResult.getTradeRecordType() == 1) {
                        tvTradeListExpenses.setText("支出¥" + commonResult.getSum() + "元，");
                    } else if (commonResult.getTradeRecordType() == 0) {
                        tvTradeListIncome.setText("收入¥" + commonResult.getSum() + "元");
                    }
                }
            }
        });
    }
}
